route.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. import { getServerSideConfig } from "@/app/config/server";
  2. import {
  3. ANTHROPIC_BASE_URL,
  4. Anthropic,
  5. ApiPath,
  6. DEFAULT_MODELS,
  7. ServiceProvider,
  8. ModelProvider,
  9. } from "@/app/constant";
  10. import { prettyObject } from "@/app/utils/format";
  11. import { NextRequest, NextResponse } from "next/server";
  12. import { auth } from "../../auth";
  13. import { isModelAvailableInServer } from "@/app/utils/model";
  14. import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare";
  15. const ALLOWD_PATH = new Set([Anthropic.ChatPath, Anthropic.ChatPath1]);
  16. async function handle(
  17. req: NextRequest,
  18. { params }: { params: { path: string[] } },
  19. ) {
  20. console.log("[Anthropic Route] params ", params);
  21. if (req.method === "OPTIONS") {
  22. return NextResponse.json({ body: "OK" }, { status: 200 });
  23. }
  24. const subpath = params.path.join("/");
  25. if (!ALLOWD_PATH.has(subpath)) {
  26. console.log("[Anthropic Route] forbidden path ", subpath);
  27. return NextResponse.json(
  28. {
  29. error: true,
  30. msg: "you are not allowed to request " + subpath,
  31. },
  32. {
  33. status: 403,
  34. },
  35. );
  36. }
  37. const authResult = auth(req, ModelProvider.Claude);
  38. if (authResult.error) {
  39. return NextResponse.json(authResult, {
  40. status: 401,
  41. });
  42. }
  43. try {
  44. const response = await request(req);
  45. return response;
  46. } catch (e) {
  47. console.error("[Anthropic] ", e);
  48. return NextResponse.json(prettyObject(e));
  49. }
  50. }
  51. export const GET = handle;
  52. export const POST = handle;
  53. export const runtime = "edge";
  54. export const preferredRegion = [
  55. "arn1",
  56. "bom1",
  57. "cdg1",
  58. "cle1",
  59. "cpt1",
  60. "dub1",
  61. "fra1",
  62. "gru1",
  63. "hnd1",
  64. "iad1",
  65. "icn1",
  66. "kix1",
  67. "lhr1",
  68. "pdx1",
  69. "sfo1",
  70. "sin1",
  71. "syd1",
  72. ];
  73. const serverConfig = getServerSideConfig();
  74. async function request(req: NextRequest) {
  75. const controller = new AbortController();
  76. let authHeaderName = "x-api-key";
  77. let authValue =
  78. req.headers.get(authHeaderName) ||
  79. req.headers.get("Authorization")?.replaceAll("Bearer ", "").trim() ||
  80. serverConfig.anthropicApiKey ||
  81. "";
  82. let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Anthropic, "");
  83. let baseUrl =
  84. serverConfig.anthropicUrl || serverConfig.baseUrl || ANTHROPIC_BASE_URL;
  85. if (!baseUrl.startsWith("http")) {
  86. baseUrl = `https://${baseUrl}`;
  87. }
  88. if (baseUrl.endsWith("/")) {
  89. baseUrl = baseUrl.slice(0, -1);
  90. }
  91. console.log("[Proxy] ", path);
  92. console.log("[Base Url]", baseUrl);
  93. const timeoutId = setTimeout(
  94. () => {
  95. controller.abort();
  96. },
  97. 10 * 60 * 1000,
  98. );
  99. // try rebuild url, when using cloudflare ai gateway in server
  100. const fetchUrl = cloudflareAIGatewayUrl(`${baseUrl}${path}`);
  101. const fetchOptions: RequestInit = {
  102. headers: {
  103. "Content-Type": "application/json",
  104. "Cache-Control": "no-store",
  105. [authHeaderName]: authValue,
  106. "anthropic-version":
  107. req.headers.get("anthropic-version") ||
  108. serverConfig.anthropicApiVersion ||
  109. Anthropic.Vision,
  110. },
  111. method: req.method,
  112. body: req.body,
  113. redirect: "manual",
  114. // @ts-ignore
  115. duplex: "half",
  116. signal: controller.signal,
  117. };
  118. // #1815 try to refuse some request to some models
  119. if (serverConfig.customModels && req.body) {
  120. try {
  121. const clonedBody = await req.text();
  122. fetchOptions.body = clonedBody;
  123. const jsonBody = JSON.parse(clonedBody) as { model?: string };
  124. // not undefined and is false
  125. if (
  126. isModelAvailableInServer(
  127. serverConfig.customModels,
  128. jsonBody?.model as string,
  129. ServiceProvider.Anthropic as string,
  130. )
  131. ) {
  132. return NextResponse.json(
  133. {
  134. error: true,
  135. message: `you are not allowed to use ${jsonBody?.model} model`,
  136. },
  137. {
  138. status: 403,
  139. },
  140. );
  141. }
  142. } catch (e) {
  143. console.error(`[Anthropic] filter`, e);
  144. }
  145. }
  146. // console.log("[Anthropic request]", fetchOptions.headers, req.method);
  147. try {
  148. const res = await fetch(fetchUrl, fetchOptions);
  149. // console.log(
  150. // "[Anthropic response]",
  151. // res.status,
  152. // " ",
  153. // res.headers,
  154. // res.url,
  155. // );
  156. // to prevent browser prompt for credentials
  157. const newHeaders = new Headers(res.headers);
  158. newHeaders.delete("www-authenticate");
  159. // to disable nginx buffering
  160. newHeaders.set("X-Accel-Buffering", "no");
  161. return new Response(res.body, {
  162. status: res.status,
  163. statusText: res.statusText,
  164. headers: newHeaders,
  165. });
  166. } finally {
  167. clearTimeout(timeoutId);
  168. }
  169. }